import { cancelOrderAPI, deleteOrderAPI } from '@/apis/consult'
import { getMedicalOrderDetailAPI } from '@/apis/order'
import { OrderType } from '@/enums'
import type { ConsultOrderItem } from '@/types/consult'
import type { OrderDetail } from '@/types/order'
import { showFailToast, showSuccessToast } from 'vant'
import { onMounted, ref } from 'vue'
// 取消订单的组合式函数
export const useCancelOrder = () => {
  // 取消的loading效果
  const cancelLoading = ref(false)
  // 取消订单
  const onCancelOrder = async (item: ConsultOrderItem) => {
    try {
      // 开启loading效果
      cancelLoading.value = true
      // 发送请求
      await cancelOrderAPI(item.id)
      // 修改 item  的 status状态
      item.status = OrderType.ConsultCancel
      // 修改 item 的 statusValue 的文字
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    } catch (error) {
      showFailToast('取消失败')
    } finally {
      // 关闭loading 效果
      cancelLoading.value = false
    }
  }
  return {
    cancelLoading,
    onCancelOrder
  }
}

// 删除订单的组合式函数
export const useDeleteOrder = (callback: () => void) => {
  // 删除的loading效果
  const deleteLoading = ref(false)
  const onDeleteOrder = async (item: ConsultOrderItem) => {
    try {
      deleteLoading.value = true
      await deleteOrderAPI(item.id)
      showSuccessToast('删除订单成功')
      // emit('on-delete', item.id)
      callback && callback()
    } catch (error) {
      showFailToast('删除订单失败')
    } finally {
      deleteLoading.value = false
    }
  }
  return {
    deleteLoading,
    onDeleteOrder
  }
}

// 获取订单详情的组合式函数
export const useOrderDetail = (id: string) => {
  // 保存药品订单详情
  const medOrderDetail = ref<OrderDetail>()
  onMounted(async () => {
    const res = await getMedicalOrderDetailAPI(id)
    // console.log(res)
    medOrderDetail.value = res.data
  })
  return {
    medOrderDetail
  }
}
